package com.huawei.chengdu.meetingdemo.view.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.device.idea.meeting.Addressbook.model.AddrBookProtocol;
import com.device.idea.meeting.Addressbook.model.AddrBookUserInfo;
import com.huawei.chengdu.meetingdemo.R;
import com.huawei.chengdu.meetingdemo.callback.MeetingCallbackSelf;
import com.huawei.chengdu.meetingdemo.presenter.ConfSdkPresenter;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ModifyContactDialog extends Dialog {
    private static final String TAG = ModifyContactDialog.class.getSimpleName();
    private static final Pattern PATTERN_CHINESE = Pattern.compile("[\\u4E00-\\u9FA5|"
            + "\\\\！|\\\\，|\\\\。|\\\\（|\\\\）|\\\\《|\\\\》|\\\\“|\\\\”|\\\\？|\\\\：|\\\\；|\\\\【|\\\\】]");

    private boolean isModifyContact = false;
    private int modifyUserId;
    private EditText contactName;
    private EditText contactIp;
    private EditText contactNumber;
    private EditText contactUri;
    private ImageView dialogExit;
    private TextView contactBandwith;
    private RadioGroup contactProtocolSelect;
    private RadioButton checkedBandwidth;
    private ImageView contactBandWidthSelect;
    private Button contactAddConfirm;
    private Context context;
    private BandwidthSelectDialog bandwidthSelectDialog;

    public ModifyContactDialog(@NonNull Context context) {
        super(context);
        this.context = context;
        setContentView(R.layout.dialog_local_contact);
        initView();
        initListener();
    }

    public ModifyContactDialog(Context context, AddrBookUserInfo modifyUserInfo) {
        this(context);
        initData(modifyUserInfo);
        isModifyContact = true;
    }


    private void initView() {
        contactName = findViewById(R.id.contact_name);
        contactNumber = findViewById(R.id.contact_number);
        contactIp = findViewById(R.id.contact_ip);
        contactUri = findViewById(R.id.contact_uri);
        contactBandwith = findViewById(R.id.contact_bandwidth);
        dialogExit = findViewById(R.id.contact_add_exit);
        contactAddConfirm = findViewById(R.id.contact_add_confirm);
        contactProtocolSelect = findViewById(R.id.contact_protocol_select);
        contactBandWidthSelect = findViewById(R.id.contact_bandwidth_select);
        bandwidthSelectDialog = new BandwidthSelectDialog(context);
    }

    private void initListener() {
        dialogExit.setOnClickListener(v -> dismiss());
        bandwidthSelectDialog.bandwidthConfirm.setOnClickListener(v -> handleBandwidthConfirm());
        contactBandWidthSelect.setOnClickListener(v -> bandwidthSelectDialog.show());
        contactAddConfirm.setOnClickListener(v -> handleContactConfirm());
    }

    private void initData(AddrBookUserInfo modifyUserInfo) {
        modifyUserId = modifyUserInfo.getId();
        contactName.setText(modifyUserInfo.getName());
        contactNumber.setText(modifyUserInfo.getLineInfo().getSiteNumber());
        contactIp.setText(modifyUserInfo.getLineInfo().getIp());
        contactUri.setText(modifyUserInfo.getLineInfo().getUrl());
        contactBandwith.setText(BandwidthSelectDialog.bandwidthMap.get(modifyUserInfo.getLineInfo().getCallRate()));
        bandwidthSelectDialog.setCheckedBandwidth(modifyUserInfo.getLineInfo().getCallRate());
        RadioButton curProtocol = (RadioButton)contactProtocolSelect.getChildAt(modifyUserInfo.getLineType().ordinal());
        curProtocol.setChecked(true);
    }

    @Override
    public void show() {
        setCanceledOnTouchOutside(false);
        super.show();
    }

    private void handleBandwidthConfirm() {
        checkedBandwidth = bandwidthSelectDialog.findViewById(bandwidthSelectDialog.bandwidthSelect.getCheckedRadioButtonId());
        contactBandwith.setText(checkedBandwidth.getText());
        bandwidthSelectDialog.dismiss();
    }

    private void handleContactConfirm() {
        AddrBookUserInfo newUserInfo = getInputUserInfo();
        if (!checkIsVaild(newUserInfo)) {
            return;
        }
        if (isModifyContact) {
            ConfSdkPresenter.modifyLocalUser(modifyUserId, newUserInfo);
        } else {
            ConfSdkPresenter.addLocalUser(newUserInfo);
        }
        ConfSdkPresenter.searchAllLocalUsers(new MeetingCallbackSelf<List<AddrBookUserInfo>>(TAG + " searchAllUsers") {
            // 统一在MeetingControlEventCallback中处理，这里不重复处理
            @Override
            public void onSuccess(List<AddrBookUserInfo> addrBookUserInfos) {}
            @Override
            public void onFailed(int errCode, String errMsg) {}
        }.getMeetingCallback());
        dismiss();
    }

    private AddrBookUserInfo getInputUserInfo() {
        checkedBandwidth = checkedBandwidth != null ? checkedBandwidth :
                bandwidthSelectDialog.findViewById(bandwidthSelectDialog.bandwidthSelect.getCheckedRadioButtonId());
        AddrBookUserInfo inputUserInfo = new AddrBookUserInfo();
        inputUserInfo.setName(contactName.getText().toString().trim());
        inputUserInfo.getLineInfo().setCallRate(Integer.parseInt(checkedBandwidth.getTag().toString()));
        inputUserInfo.getLineInfo().setIp(contactIp.getText().toString().trim());
        inputUserInfo.getLineInfo().setUrl(contactUri.getText().toString().trim());
        inputUserInfo.getLineInfo().setSiteNumber(contactNumber.getText().toString().trim());
        RadioButton checkedProtocol = findViewById(contactProtocolSelect.getCheckedRadioButtonId());
        inputUserInfo.setLineType(AddrBookProtocol.getProtocol(Integer.parseInt(checkedProtocol.getTag().toString())));
        return inputUserInfo;
    }

    private boolean checkIsVaild(AddrBookUserInfo newUserInafo) {
        if ("".equals(newUserInafo.getName())) {
            Toast.makeText(context, "请输入名称", Toast.LENGTH_LONG).show();
            return false;
        }
        if (newUserInafo.getName().contains(System.lineSeparator())) {
            Toast.makeText(context, "名称含有非法字符，请重新输入", Toast.LENGTH_LONG).show();
            return false;
        }
        if (newUserInafo.getLineInfo().getUrl().contains(" ") || newUserInafo.getLineInfo()
                .getUrl()
                .contains(System.lineSeparator()) || checkisContainChinese(newUserInafo.getLineInfo().getUrl())) {
            Toast.makeText(context, "URI含有非法字符，请重新输入", Toast.LENGTH_LONG).show();
            return false;
        }
        if (newUserInafo.getLineInfo().getSiteNumber().contains(" ") || newUserInafo.getLineInfo()
                .getSiteNumber()
                .contains(System.lineSeparator()) || checkisContainChinese(newUserInafo.getLineInfo().getSiteNumber())) {
            Toast.makeText(context, "号码含有非法字符，请重新输入", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    private boolean checkisContainChinese(String str) {
        Matcher matcher = PATTERN_CHINESE.matcher(str);
        if (matcher.find()) {
            return true;
        }
        return false;
    }
}
